package com.example.demo;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.io.IOException;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;

@RestController
@RequestMapping("/api/recording")
public class RecordingController {

    private String recordingPath="";

    private Process recordingProcess;
    private static String ffmpegPath = "D:\\jdk18\\ffmpeg-4.3.1-full_build\\bin\\ffmpeg";

    @GetMapping("/start")
    public ResponseEntity<String> startRecording() throws IOException {
        if (recordingProcess != null && recordingProcess.isAlive()) {
            return ResponseEntity.badRequest().body("Recording already in progress");
        }

        String outputFile = recordingPath + "/recording_" +
                LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyy-MM-dd_HH-mm-ss")) + ".mp4";
        String[] cmd = {
                ffmpegPath,
                "-i", "rtsp://127.0.0.1:554/easy1.mp4",
                "-rtsp_transport", "tcp",  // 强制使用TCP传输(对于RTSP)
                "-c:v", "copy",             // 视频流直接复制
                "-c:a", "copy",             // 音频流直接复制
                "-f", "mp4",
                "-y",
                "D:\\jdk18\\hls1\\test1.mp4"
        };

        recordingProcess = new ProcessBuilder(cmd).start();
        return ResponseEntity.ok("Recording started: " + outputFile);
    }

    @GetMapping("/stop")
    public ResponseEntity<String> stopRecording() {
        if (recordingProcess == null || !recordingProcess.isAlive()) {
            return ResponseEntity.badRequest().body("No active recording");
        }

        recordingProcess.destroy();
        return ResponseEntity.ok("Recording stopped");
    }
}